import axios from "axios";
import crypto from 'crypto';
import qs from "qs";
import assist from '../request/assist'
// import { Toast } from "vant";
// import bridge from "../http/bridge";

var AppId = 'h51.0';
var UDID = '62d5521f-58bc-3a13-ac22-d2cc6569504a';
// axios.defaults.baseURL = 'http://h51.babylittlebear.com/api/v2/';//线上打包
// axios.defaults.baseURL = 'http://local3.api.com/api/v2/';//本地打包
// axios.defaults.baseURL = '/api';//本地测试

// 请求超时设置 10s
// axios.defaults.timeout = 10000;//复制代码
// post请求头的设置
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// 添加响应拦截器
/*axios.interceptors.response.use(
	(response) => {
	  let { data } = response
	  return data
	},
	(error) => {
	  if (!error.response) {
		info = {
		  code: 5000,
		  msg: 'Network Error'
		}
	  } else {
		// 此处整理错误信息格式
		console.log(error.response.data.status_code +"监听到的错误信息");
		console.log(error.response.data.message);
		if(error.status == 404){
			console.log("访问请求服务器出错")
		}else{
			if(error.response.data.status_code == 401){
				// bridge.loseToken(); //401调用
			}else if(error.response.data.status_code == 404){

			}else{
				Toast(error.response.data.message);
			}
		}
	  }
	}
  )*/
// get请求
function GET(url, params, headers) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params,
			headers: headers
		}).then(res => {
			resolve(res);
		}).catch(err => {
			reject(err);
		})
	})
}

// post请求
function POST(url,params,headers){
    return new Promise((resolve, reject) => {
		axios.post(url, qs.stringify(params),{
			headers: headers
		}).then(res => {
			resolve(res);
		}).catch(err => {
			reject(err);
		})
	})
}

// 获取请求头
function getSign(params,UID) {
	var Appsec = 'b4725c7e8fa004594d5c7cb92a0ea282';
	var TimeStamp = Math.round(new Date().getTime() / 1000).toString();
	var NonceStr = TimeStamp + 'NonceStr';
	var arys = {
		'AppId': AppId,
		'UDID': UID,
		'TimeStamp': TimeStamp,
		'NonceStr': NonceStr
	}
	console.log(arys.NonceStr+'77777777');
	var arr = Object.keys(params);
	if (arr.length > 0) {
		for (var i = 0; i < arr.length; i++) {
			arys[arr[i]] = params[arr[i]];
		}
	}
	var finalArr = objKeySort(arys);
	var str = '';
	for (var x in finalArr) {
		str += x + "=" + finalArr[x] + "&"
	}
	str += 'key=' + Appsec;
	var Sign = md5(str).toUpperCase();
	return {
		'UDID': UID,
		'TimeStamp': TimeStamp,
		'NonceStr': NonceStr,
		'Sign': Sign
	}
}
// ascii码升序
function objKeySort(arys) {
	var newkey = Object.keys(arys).sort();
	var newObj = {};
	for (var i = 0; i < newkey.length; i++) {
		newObj[newkey[i]] = arys[newkey[i]];
	}
	return newObj;
}
// md5加密
function md5(text) {
	return crypto.createHash('md5').update(text).digest('hex')
}



export default{
    GET:GET,
    POST:POST,
	getSign:getSign
}

